//
// Created by tang on 2022/10/24.
//

#include "vertex_arrary.hpp"
#include "buffer.hpp"

namespace GL
{
    VertexArray::VertexArray(GLuint buffer_cnt) : m_handle_(0), m_buffer_cnt_(buffer_cnt) {
        assert(buffer_cnt > 0 && buffer_cnt <= MAX_BUFFER_CNT);
        for (GLuint i=0; i<buffer_cnt; ++i)
        {
            m_buffers_[i] = std::make_shared<Buffer>();
        }
        GLCallValidation(glGenVertexArrays(1, &m_handle_));
    }

    VertexArray::~VertexArray() {
        GLCallValidation(glDeleteVertexArrays(1, &m_handle_));
    }

    void VertexArray::Bind() const {
        GLCallValidation(glBindVertexArray(m_handle_));
    }

    void VertexArray::UnBind() {
        if (m_handle_ > 0)
            GLCallValidation(glBindVertexArray(0));
    }

    BufferPtr VertexArray::Get(GLuint index) const {
        return (*this)[index];
    }

    BufferPtr VertexArray::operator[](GLuint index) const {
        assert(index < m_buffer_cnt_);
        return m_buffers_[index];
    }

    VertexArrayPtr VertexArray::Create(GLuint buffer_cnt) {
        return std::make_unique<VertexArray>(buffer_cnt);
    }
}
